import superagent from 'superagent';
require('superagent-charset')(superagent)
import cheerio from 'cheerio';

const searchTxt = async (data) => {
    // const baseURL = 'http://www.pksge.org/modules/article/search.php';
     const baseURL = 'http://www.pksge.la/modules/article/search.php' // 2024/12/17 更换域名
    try {
        const res = await superagent.post(baseURL)
            .field('searchkey', data)
            .field('searchtype', 'articlename')
            .charset('UTF-8')
            .buffer(true);
        return res;
    } catch (error) {
        console.error(error);
        return null;
    }
}
const getSection = async (url, current) => {
    let urls = [];
    const response = await superagent.get(url).charset('UTF-8').buffer(true);
    const $ = cheerio.load(response.text);
    // 提取链接
    $('.zhangjiekaishi ul li a').each((i, v) => {
        let link = url + $(v).attr('href');
        urls.push(link);
    });
    let section = await getSectionContent(urls[current], current);
    return {
        ...section,
        total: urls.length
    }
}
const getSectionContent = async (url,current) => {
    const res = await superagent.get(url).charset('UTF-8').buffer(true);
    let $ = cheerio.load(res.text);
    let section = {
        sectionName: `第${current+1}章` + $('h1').text(),
        sectionContent: reconvert($)
    }
    return section;
}
function reconvert($) {
    let content = ``
    $("div#booktext").each((index, ele) => {
        content += $(ele).text()
    })
    return content
}
export { searchTxt, getSection };